package com.j2data.spike.rabbitmq;

import com.j2data.spike.pojo.SpikeMessage;
import com.j2data.spike.pojo.SpikeOrder;
import com.j2data.spike.pojo.User;
import com.j2data.spike.service.IGoodsService;
import com.j2data.spike.service.IOrderService;
import com.j2data.spike.utils.JsonUtil;
import com.j2data.spike.vo.GoodsVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @author j2data
 * @version 1.0
 */
@Service
@Slf4j
public class MQReceiver {

    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IOrderService orderService;
    /**
     * 下单操作
     *
     * @param message
     */
    @RabbitListener(queues = "spikeQueue")
    public void receive(String message) {
        log.info("接收的消息:" + message);
        SpikeMessage spikeMessage = JsonUtil.jsonStr2Object(message, SpikeMessage.class);
        Long goodsId = spikeMessage.getGoodsId();
        User user = spikeMessage.getUser();
        GoodsVo goodsVo = goodsService.findGoodsVoByGoodsId(goodsId);
        //库存判断
        if (goodsVo.getStockCount() < 1) {
            return;
        }
        //判断是否重复抢购
        SpikeOrder spikeOrder = (SpikeOrder)redisTemplate.opsForValue().get("order:"+user.getId()+":"+goodsId);
        if (spikeOrder!=null) {
            return;
        }
        //下单操作
        orderService.spike(user,goodsVo);
    }
}
